<?php
################################################################################################
#  DIY Module Builder for Opencart 1.5.1.x From HostJars http://opencart.hostjars.com  		   #
################################################################################################
class ControllerModuleTFilter extends Controller {
	
	private $error = array(); 
	
	public function manage() {   
		$this->load->language('module/t_filter');

		$this->document->setTitle($this->language->get('heading_manage'));
		
		$this->load->model('setting/setting');
		
		
		$text_strings = array(
				'heading_manage',
				'text_enabled',
				'text_disabled',
				'text_content_top',
				'text_content_bottom',
				'text_column_left',
				'text_column_right',
				'entry_layout',
				'entry_limit',
				'entry_position',
				'entry_status',
				'entry_sort_order',
				'button_save',
				'button_cancel',
				'button_add_module',
				'button_remove',
				'button_remove_range_item',
				'text_name',
				'text_range',
				'text_sort_order',
				'text_limited_by',
				'text_attribute',
				'text_attribute_group',
				'text_category',
				'text_manufacturer',
				'text_only_stock',
				'button_edit_items',
				'text_item_type',
				'text_display',
				'text_range',
				'text_multiple',
				'text_product_field',
				'text_select',
				'text_list',
				'text_min',
				'text_max',
				'button_new',
				'text_item_title',
				'text_add_item',
				'text_remove_item',
				'text_add_filter',
				'text_nothing',
				'day_su',
				'day_mo',
				'day_tu',
				'day_we',
				'day_th',
				'day_fr',
				'day_sa',
				'month_jenuary',
				'month_february',
				'month_march',
				'month_april',
				'month_may',
				'month_june',
				'month_july',
				'month_august',
				'month_september',
				'month_october',
				'month_november',
				'month_december',
				'text_check_all',
				'text_uncheck_all',
				'text_none_selected',
				'text_selected'
				
		);
		
		
		foreach ($text_strings as $text) {
			$this->data[$text] = $this->language->get($text);
		}
	
 		if (isset($this->error['warning'])) {
			$this->data['error_warning'] = $this->error['warning'];
		} else {
			$this->data['error_warning'] = '';
		}
		
  		$this->data['breadcrumbs'] = array();

   		$this->data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('text_home'),
			'href'      => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
      		'separator' => false
   		);

   		$this->data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('text_module'),
			'href'      => $this->url->link('extension/module', 'token=' . $this->session->data['token'], 'SSL'),
      		'separator' => ' :: '
   		);
		
   		$this->data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('heading_title'),
			'href'      => $this->url->link('module/t_filter', 'token=' . $this->session->data['token'], 'SSL'),
      		'separator' => ' :: '
   		);
   		
   		$this->data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('heading_manage'),
			'href'      => $this->url->link('module/t_filter/manage', 'token=' . $this->session->data['token'], 'SSL'),
      		'separator' => ' :: '
   		);
		
		$this->data['action'] = $this->url->link('module/t_filter/manage', 'token=' . $this->session->data['token'], 'SSL');
		
		$this->data['cancel'] = $this->url->link('module/t_filter', 'token=' . $this->session->data['token'], 'SSL');
		

		$this->template = 'module/t_filter_manage.tpl';
		$this->children = array(
			'common/header',
			'common/footer',
		);
		
		$this->load->model('module/t_filter');
		
		$this->saveFilters();
		
		$this->data["filters"]=$this->model_module_t_filter->getFilters();
		foreach($this->data["filters"] as $key=>$filter)
		{
			$this->data["filters"][$key]["items"]=$this->model_module_t_filter->getFilterItems($filter["filter_id"]);
			$this->data["filters"][$key]["instock"]=explode(",",$filter["instock"]);
		}
		$this->data["stock_status"]=$this->model_module_t_filter->getStockStatus();
		$this->data["attributes"]=$this->model_module_t_filter->getAttributes();
		$this->data["attribute_groups"]=$this->model_module_t_filter->getAttributeGroups();
		$this->data["categories"]=$this->model_module_t_filter->getCategories();
		$this->data["manufacturers"]=$this->model_module_t_filter->getManufacturers();
		$pfs=array(
			'price',
			'category',
			'model',
			'manufacturer_id',
			'date_added',
			'date_available',
			'points',
			'shipping',
			'minimum',
			'tax_class_id',
			'weight',
			'length',
			'width',
			'height'
			
		);
		$this->data["product_fields"]=array();
		foreach($pfs as $pf)
		{
			$this->data["product_fields"][$pf]=array('field'=>$pf,'text'=>$this->language->get($pf),'numeric'=>false,'date'=>false);
		}
		
		$this->data["product_fields"]["price"]["numeric"]=true;
		$this->data["product_fields"]["weight"]["numeric"]=true;
		$this->data["product_fields"]["length"]["numeric"]=true;
		$this->data["product_fields"]["width"]["numeric"]=true;
		$this->data["product_fields"]["height"]["numeric"]=true;
		
		$this->data["product_fields"]["date_added"]["date"]=true;
		$this->data["product_fields"]["date_available"]["date"]=true;

		//Send the output.
		
		$this->document->addStyle('view/stylesheet/t_filter/jquery.multiselect.css');
		$this->response->setOutput($this->render());
	}
	
	private function saveFilters()
	{
		if(!isset($this->request->post["filter"]))
		{
			return false;
		}
		$t_model=$this->model_module_t_filter;
		$filters=$this->request->post["filter"];
		$fids=array();
		foreach($filters as $filter_key=>$filter)
		{
			if(is_numeric($filter_key))
			{
				$t_model->updateFilter($filter_key,$filter);
				$fids[]=$filter_key;
			}
			else
			{
				$fids[]=$t_model->insertFilter($filter);
			}
			if(isset($filter["items"]))
			{
				$iids=array();
				foreach($filter["items"] as $item_key=>$item)
				{
					$item["filter_id"]=$filter["filter_id"];
					if(isset($item["range"]["exists"]) && $item["range"]["exists"])
					{
						$range=array();
						foreach($item["range"]["min"] as $range_key=>$minval)
						{
							$maxval=$item["range"]["max"][$range_key];
							$range[]=array("min"=>$minval,"max"=>$maxval);
						}
						$item["range"]=$range;
					}
					else
					{
						$item["range"]=array();
					}
					if($item["item_type"]=='pf')
					{
						$item["product_field"]=$item["item_id_pf"];
						$item["item_id"]='';
					}
					else
					{
						$item["item_id"]=$item["item_id_pf"];
						$item["product_field"]='';
					}
					$item["multiple"]=(isset($item["multiple"]))?$item["multiple"]:0;
					if(is_numeric($item_key))
					{
						$t_model->updateItem($item_key,$item);
						$iids[]=$item_key;
					}
					else
					{
						$iids[]=$t_model->insertItem($item);
					}
				}
			}
			
			$t_model->cleanFilter($filter_key,$iids);
		}
		
		$t_model->eleminateFilters($fids);
	}
	
	public function index() {   
		//Load the language file for this module
		$this->load->language('module/t_filter');

		//Set the title from the language file $_['heading_title'] string
		$this->document->setTitle($this->language->get('heading_title'));
		
		//Load the settings model. You can also add any other models you want to load here.
		$this->load->model('setting/setting');
		
		//Save the settings if the user has submitted the admin form (ie if someone has pressed save).
		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
			$this->model_setting_setting->editSetting('t_filter', $this->request->post);		
					
			//$this->session->data['success'] = $this->language->get('text_success');
						
			//$this->redirect($this->url->link('extension/module', 'token=' . $this->session->data['token'], 'SSL'));
		}

		//This is how the language gets pulled through from the language file.
		//
		// If you want to use any extra language items - ie extra text on your admin page for any reason,
		// then just add an extra line to the $text_strings array with the name you want to call the extra text,
		// then add the same named item to the $_[] array in the language file.
		//
		// 't_filter_example' is added here as an example of how to add - see admin/language/english/module/t_filter.php for the
		// other required part.
		
		$text_strings = array(
				'heading_title',
				'text_enabled',
				'text_disabled',
				'text_content_top',
				'text_content_bottom',
				'text_column_left',
				'text_column_right',
				'entry_filters',
				'entry_layout',
				'entry_limit',
				'entry_position',
				'entry_status',
				'entry_sort_order',
				'button_save',
				'button_cancel',
				'button_add_module',
				'button_remove',
				'button_manage' //this is an example extra field added
		);
		
		foreach ($text_strings as $text) {
			$this->data[$text] = $this->language->get($text);
		}
		//END LANGUAGE
		
		//The following code pulls in the required data from either config files or user
		//submitted data (when the user presses save in admin). Add any extra config data
		// you want to store.
		//
		// NOTE: These must have the same names as the form data in your t_filter.tpl file
		//
	
		//This creates an error message. The error['warning'] variable is set by the call to function validate() in this controller (below)
 		if (isset($this->error['warning'])) {
			$this->data['error_warning'] = $this->error['warning'];
		} else {
			$this->data['error_warning'] = '';
		}
		
		//SET UP BREADCRUMB TRAIL. YOU WILL NOT NEED TO MODIFY THIS UNLESS YOU CHANGE YOUR MODULE NAME.
  		$this->data['breadcrumbs'] = array();

   		$this->data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('text_home'),
			'href'      => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
      		'separator' => false
   		);

   		$this->data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('text_module'),
			'href'      => $this->url->link('extension/module', 'token=' . $this->session->data['token'], 'SSL'),
      		'separator' => ' :: '
   		);
		
   		$this->data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('heading_title'),
			'href'      => $this->url->link('module/t_filter', 'token=' . $this->session->data['token'], 'SSL'),
      		'separator' => ' :: '
   		);
		
		$this->data['action'] = $this->url->link('module/t_filter', 'token=' . $this->session->data['token'], 'SSL');
		
		$this->data['cancel'] = $this->url->link('extension/module', 'token=' . $this->session->data['token'], 'SSL');
		
		$this->data['link_manage'] = $this->url->link('module/t_filter/manage', 'token=' . $this->session->data['token'], 'SSL');

	
		//This code handles the situation where you have multiple instances of this module, for different layouts.
		$this->data['modules'] = array();
		
		if (isset($this->request->post['t_filter_module'])) {
			$this->data['modules'] = $this->request->post['t_filter_module'];
		} elseif ($this->config->get('t_filter_module')) { 
			$this->data['modules'] = $this->config->get('t_filter_module');
		}		

		$this->load->model('design/layout');
		
		$this->data['layouts'] = $this->model_design_layout->getLayouts();

		//Choose which template file will be used to display this request.
		$this->template = 'module/t_filter.tpl';
		$this->children = array(
			'common/header',
			'common/footer',
		);
		
		$this->load->model('module/t_filter');
		$this->data["filters"]=$this->model_module_t_filter->getFilters();
		if(empty($this->data["filters"]))
		{
			$this->redirect($this->url->link('module/t_filter/manage', 'token=' . $this->session->data['token'], 'SSL'));
		}

		//Send the output.
		$this->response->setOutput($this->render());
	}
	
	/*
	 * 
	 * This function is called to ensure that the settings chosen by the admin user are allowed/valid.
	 * You can add checks in here of your own.
	 * 
	 */
	private function validate() {
		if (!$this->user->hasPermission('modify', 'module/t_filter')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}
		
		if (!$this->error) {
			return TRUE;
		} else {
			return FALSE;
		}	
	}

	public function install()
	{
		$this->load->model('module/t_filter');
		$this->model_module_t_filter->dropModuleTables();
		$this->model_module_t_filter->createModuleTables();
		$this->model_module_t_filter->addLayout();
	}
	
	public function uninstall()
	{
		$this->load->model('module/t_filter');
		$this->model_module_t_filter->removeLayout();
		$this->model_module_t_filter->dropModuleTables();
	}
}
?>